package com.xtkj.superclub_information.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xtkj.commons.JsonParse;
import com.xtkj.commons.JsonResult;
import com.xtkj.superclub_entity.entity.travel.Travel;
import com.xtkj.superclub_entity.entity.travel.TravelPraise;
import com.xtkj.superclub_entity.entity.user.User;
import com.xtkj.superclub_information.client.IUserClient;
import com.xtkj.superclub_information.dao.TravelDao;
import com.xtkj.superclub_information.dao.TravelPraiseDao;
import com.xtkj.superclub_information.service.ITravelPraiseService;
import feign.Feign;
import io.goeasy.GoEasy;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * @author lizheqi
 * @create 2020-01-04-10:04
 */

@Service
@RabbitListener(queues = "praiseQueue")
public class TravelPraiseServiceImpl implements ITravelPraiseService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TravelPraiseDao travelPraiseDao;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 游记点赞推送功能
     */
    @RabbitHandler
    @Override
    public void addPraise(String info) {
        //通过info获取游记编号由点赞用户编号
        String[] split = info.split("-");
        String pcs = split[0];//游记编号
        String key = split[1];//用户编号
        String message = split[2];
        System.out.println(message);
        HashOperations ops = redisTemplate.opsForHash();
        //先判断数据库里面有没有对应的该键
        if(ops.hasKey(pcs,key)){//如果缓存里面有该键存在，则删除此键
            ops.delete(pcs,key);
            UpdateWrapper<TravelPraise> wrapper = new UpdateWrapper<>();
            wrapper.eq("travel_id",pcs).eq("user_id",key);
            //并将该点赞人的信息删除
            travelPraiseDao.delete(wrapper);
        }else{
            ops.put(pcs,key,1);//表示点赞
            //推送消息时将点赞人与游记编号存放到点赞表
            TravelPraise travelPraise = new TravelPraise();
            travelPraise.setTravelId(pcs).setUserId(key).setCreatedtm(new Date()).setUpdatedtm(new Date());
            travelPraiseDao.insert(travelPraise);
            GoEasy goEasy = new GoEasy("https://rest-hangzhou.goeasy.io","BC-a0fc31b1194e4581b857caa6c2d7c8c9");
            goEasy.publish("my_channel", message);
        }
    }
}
